package com.xudow.app.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.vo.ScheduleVO;
import com.xudow.app.R;
import com.xudow.app.ui.task.ClazzScheduleTask;
import com.xudow.app.util.TimeUtils;
import com.xudow.app.util.Maps;
import com.xudow.app.util.WeekCalendar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * 课程表Activity
 *
 * @author lukecheng
 */
public class ClazzScheduleActivity extends BaseActivity
        implements WeekChoosePopupWindow.OnOkClickListner,
        ClassScheduleFragment.OnScheduleViewClickListener {

    private static final String TAG = makeLogTag(ClazzScheduleActivity.class);

    private TextView titleView;
    private WeekChoosePopupWindow weekChoosePopupWindow;
    private ClassScheduleFragment classScheduleFragment;

    private int curYear; //当前年
    private int curMonth; //当前月
    private int curWeek; //当前周

    private String studentId;  //学生id

    private ClazzScheduleTask clazzScheduleTask;

    private List<ScheduleVO> scheduleVOList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clazz_schedule);

        studentId = getIntent().getStringExtra("studentId");

        LOGE("zxj", "studentId = " + studentId);

        titleView = (TextView) findViewById(R.id.title);

        Date curDate = new Date();
        curYear = TimeUtils.getYear(curDate);
        curMonth = TimeUtils.getMonthNum(curDate);
        curWeek = TimeUtils.getWeekNum(curDate);
        String title = getString(R.string.week_prompt, curYear, curMonth, curWeek);
        titleView.setText(title);

        FragmentManager fm = getSupportFragmentManager();
        classScheduleFragment = (ClassScheduleFragment) fm.findFragmentById(R.id.fragment_schedule);

        loadSchedules();
    }

    public void onBackBtnClick(View view) {
        finish();
    }

    /**
     * 标题周选择点击事件
     *
     * @param view
     */
    public void onTitleClick(View view) {
        weekChoosePopupWindow = new WeekChoosePopupWindow(this, curYear, curMonth, curWeek);
        weekChoosePopupWindow.setOkClickListner(this);
        weekChoosePopupWindow.showAtLocation(findViewById(R.id.root),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void onOkClick(int year, int month, int week) {
        curYear = year;
        curMonth = month;
        curWeek = week;

        String title = getString(R.string.week_prompt, curYear, curMonth, curWeek);
        titleView.setText(title);

        weekChoosePopupWindow.dismiss();

        classScheduleFragment.updateDayViews(curYear, curMonth, curWeek);

        loadSchedules();
    }

    /**
     * 加载课表
     */
    private void loadSchedules() {
        if (null == studentId) {
            classScheduleFragment.setSchedules(new ArrayList<ScheduleVO>());
            return;
        }

        showLodingDialog(getString(R.string.loading));

        String dayWithMonth = getFirstDayOfWeek();
        String[] daySegments = dayWithMonth.split("-");

        HashMap<String, String> params = Maps.newHashMap();
        params.put("studentid", studentId);
        params.put("weekBeginDate", String.format("%s-%s-%s", daySegments[0], daySegments[1], daySegments[2]));

        clazzScheduleTask = new ClazzScheduleTask(this, scheduleHandler);
        addTask(clazzScheduleTask);
        clazzScheduleTask.execute(params);
    }

    private Handler scheduleHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (ClazzScheduleTask.SUCCESS == msg.what) {
                scheduleVOList = new ArrayList<ScheduleVO>();

                ScheduleVO[] result = (ScheduleVO[]) msg.getData().getSerializable("schedules");
                scheduleVOList.addAll(Arrays.asList(result));

                classScheduleFragment.setSchedules(scheduleVOList);
                classScheduleFragment.setOnScheduleViewClickListener(ClazzScheduleActivity.this);
            } else {
                classScheduleFragment.setSchedules(new ArrayList<ScheduleVO>());

                String message = getString(R.string.loading_fail);
                Toast.makeText(ClazzScheduleActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    public String getFirstDayOfWeek() {
        WeekCalendar wc = new WeekCalendar(curYear, curMonth, curWeek);
        String[] days = wc.getWeekDaysWithMonthYear();

        return days[0];
    }

    @Override
    public void onScheduleClick(ScheduleVO vo) {
        try {
            ClazzScheduleDetailPopupWindow popupWindow = new ClazzScheduleDetailPopupWindow(this, vo);
            popupWindow.showAtLocation(findViewById(R.id.root),
                    Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    }
}
